from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import Brand
from meiduo_admin.serializer.brands import BrandSerializer
from meiduo_admin.utils import PageNum


class BrandView(ModelViewSet):
    # 权限指定
    permission_classes = [IsAdminUser]
    # 序列化器指定
    serializer_class = BrandSerializer
    # 分页器指定
    pagination_class = PageNum
    # 查询集指定
    queryset = Brand.objects.all()


    def create(self, request, *args, **kwargs):
        # 获取要保存的图片对象
        data = request.FILES.get('logo')
        # 验证图片数据
        if data is None:
            return Response(status=500)
        # 建立fastFDS 的链接对象
        client = Fdfs_client(settings.FASTDFS_CONF)
        # 上传图片数据
        res = client.upload_by_buffer(data.read())
        # 判断上传状态
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        # 获取上传的图片路径
        logo_url = res['Remote file_id']

        name = request.data.get('name')
        first_letter = request.data.get('first_letter')

        brand = Brand.objects.create(name=name,first_letter=first_letter,logo=logo_url)

        # 结果返回
        return Response(
            {
                'name':brand.name,
                'first_letter':brand.first_letter,
                'logo':brand.logo
            },
            status=201
        )

    def update(self, request, *args, **kwargs):
        # 获取要保存的图片对象
        data = request.FILES.get('logo')
        # 验证图片数据
        if data is None:
            return Response(status=500)
        # 建立fastFDS 的链接对象
        client = Fdfs_client(settings.FASTDFS_CONF)
        # 上传图片数据
        res = client.upload_by_buffer(data.read())
        # 判断上传状态
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        # 获取上传的图片路径
        logo_url = res['Remote file_id']

        brand = Brand.objects.get(id=kwargs['pk'])

        brand.name = request.data['name']
        brand.logo = logo_url
        brand.first_letter = request.data['first_letter']
        brand.save()

        return Response(
            {
                'name': brand.name,
                'first_letter': brand.first_letter,
                'logo': brand.logo
            },
            status=201
        )